package CliGui;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import static java.lang.System.exit;

//这是当连接服务器的客户端数>=2时，选择要聊天的客户端的界面
public class ChoiceGui extends JFrame{
    private int local = 0;
    private int Choiceflag = 1;

    private static int choice = -5;

    public ChoiceGui(int f,int l){
        Choiceflag = f;
        local = l;
        init();
    }

    public void init(){
        JTextField Tlocal = new JTextField("当前客户端序号为："+local);
        JTextField Tchoice = new JTextField("目前可供选择的客户端为0~"+(Choiceflag-1));
        JTextField Tpls = new JTextField("请选择一个客户端进行连接。");
        JTextField Ttips = new JTextField("(选择本地序号则是和自己通话)");

        //居中
        Tlocal.setHorizontalAlignment(SwingConstants.CENTER);
        Tchoice.setHorizontalAlignment(SwingConstants.CENTER);
        Tpls.setHorizontalAlignment(SwingConstants.CENTER);
        Ttips.setHorizontalAlignment(SwingConstants.CENTER);

        //关闭边框
        Tlocal.setBorder(null);
        Tchoice.setBorder(null);
        Tpls.setBorder(null);
        Ttips.setBorder(null);

        //设置字体
        Tlocal.setFont(new Font("宋体",Font.PLAIN,23));
        Tchoice.setFont(new Font("宋体",Font.PLAIN,23));
        Tpls.setFont(new Font("宋体",Font.PLAIN,23));
        Ttips.setFont(new Font("宋体",Font.PLAIN,23));

        JButton confirm = new JButton("确定");
        JButton exit = new JButton("退出");

        JTextField input = new JTextField("");
        input.setFont(new Font("宋体",Font.PLAIN,23));

        setBounds(300,300,400,400);

        setLayout(new GridLayout(7,1));

        add(Tlocal);
        add(Tchoice);
        add(Ttips);
        add(Tpls);
        add(input);
        add(confirm);
        add(exit);

        setVisible(true);

        //添加事件监听
        input.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                int key = e.getKeyCode();
                if(key == KeyEvent.VK_ENTER){
                    choice = Integer.parseInt(input.getText());
                    input.setText("");
                    System.out.println(choice);
                    dispose();
                }
            }
        });

        confirm.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                choice = Integer.parseInt(input.getText());
                input.setText("");
                System.out.println(choice);
                dispose();
            }
        });

        exit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("退出");
                exit(0);
            }
        });
    }

    //获得choice
    public static int getChoice(){
        return choice;
    }

}
